<template>
  <div class="department-container">
    <div class="app-container">
      <PageTools title="总记录数据20条">
        <el-button
          v-allow="'import_employee'"
          type="warning"
          size="small"
          round
          @click="$router.push('/import')"
        >excel导入</el-button>
        <el-button
          v-allow="'export_employee'"
          type="danger"
          size="small"
          round
          @click="hExport"
        >excel导出</el-button>
        <el-button
          type="primary"
          size="small"
          @click="showDialog = true"
        >新增员工</el-button>
      </PageTools>
      <el-card style="margin-top: 10px">
        <el-table border :data="employee">
          <el-table-column type="index" label="序号" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="workNumber" label="工号" />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template slot-scope="scope">
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" />
          <!-- <el-table-column prop="username" label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="hDel(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :total="total"
            :current-page="page"
            :page-size="size"
            :page-sizes="[2,5,10,20]"
            layout="total,sizes,prev, pager, next"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>

      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hClose">
        <addor-edit
          ref="addorEdit"
          @close="showDialog = false"
          @success="hSuccess"
        />
      </el-dialog>

      <el-dialog title="分配角色" :visible.sync="showDialogRole">
        <assign-role v-if="showDialogRole" ref="assignRole" :cur-id="curId" @success="hSuccessRole" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployee, delEmployee } from '@/api/employees'
import { TYPE_MAP } from '@/constant/index'
import addorEdit from './component/empDialog.vue'
import AssignRole from './component/assignRole.vue'
export default {
  components: { addorEdit, AssignRole },

  data() {
    return {
      employee: [],
      page: 1, // 当前页码
      size: 10, // 每页几条
      total: 0, // 总共数据条数
      showDialog: false,
      showDialogRole: false,
      curId: ''
    }
  },
  created() {
    // this.hello()
    // console.log('created', this, this.num)
    this.loadEmployee()
  },
  methods: {
    hSuccessRole() {
      this.showDialogRole = false
      this.$message.success('保存成功')
    },
    hAssignRole(id) {
      console.log(id)
      this.curId = id
      this.showDialogRole = true
    },
    formatData(list) {
      // const map = {
      //   'id': '编号',
      //   'password': '密码',
      //   'mobile': '手机号',
      //   'username': '姓名',
      //   'timeOfEntry': '入职日期',
      //   'formOfEmployment': '聘用形式',
      //   'correctionTime': '转正日期',
      //   'workNumber': '工号',
      //   'departmentName': '部门',
      //   'staffPhoto': '头像地址'
      // }
      console.log(list)
      // let header = []
      // header = ['id', 'mobile', 'username', .....]
      // data = [
      //     ['65c2', '1380000002', '管理员', ....],
      //     ['65c3', '1380000003', '孙财', ....],
      // ]
      // let data = []
      // 开始代码
      // 找到一个元素
      // const one = list[0]
      // if (!one) {
      //   return { header, data }
      // }
      // header = Object.keys(one).map(key => {
      //   return map[key]
      // })
      // 表头
      const header = Object.keys(list[0])
      // 内容
      const data = list.map(obj => { return Object.values(obj) })
      // data把list中每一个对象转成 对应的value数组
      // data = list.map(obj => {
      //   // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
      //   const key = obj['formOfEmployment'] // 1, 2
      //   obj['formOfEmployment'] = TYPE_MAP[key] // hireTypEnmu:{1:'正式', '2':'非正式' }

      //   return Object.values(obj)
      // })

      return { header, data }
    },
    async hExport() {
      const res = await getEmployee({ page: this.page, size: this.size })
      const { header, data } = this.formatData(res.data.rows)
      console.log('员工信息', header, data)
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        // console.log(excel)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '员工信息', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    hClose() {
      this.$refs.addorEdit.formData = {}
      // 清空子组件的表单数据 & 校验结果
      // 思路：在子组件内部提供一个方法，在父组件调用
      this.$refs.addorEdit.resetFields()
    },
    hSuccess() {
      console.log('子组件添加成功')
      // 1. 关闭弹层
      this.showDialog = false
      this.total++// 添加成功，进入最后一页看数据
      this.pageParams.page = Math.ceil(this.total / this.pageParams.size)// 最后一页
      // 2. 更新数据
      this.loadEmployee()
    },
    // 删除
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log('delEmployee', res)
        // 如果删除第最后一页（例如4）的最一条数据之后，页面会显示不正常
        if (this.employee.length === 1) {
          if (this.page > 1) {
            this.page--
          }
        }
        this.$message.success('删除成功')
        // 重发请求
        this.loadEmployee()
      } catch (err) {
        console.log('delEmployee', err)
      }
    },
    hDel(id) {
      console.log(id)
      this.$confirm('确认删除吗？').then(() => {
        this.doDel(id)
      }).catch(() => {})
    },
    format(type) {
      return TYPE_MAP[type] || '未知'
    },
    async loadEmployee() {
      const res = await getEmployee({ page: this.page, size: this.size })
      console.log('员工信息', res)
      // 保存
      this.employee = res.data.rows
      this.total = res.data.total
    },
    // 更改每页显示几条数据
    hSizeChange(curPagesize) {
      console.log(curPagesize)
      // 1. 更新参数
      this.size = curPagesize
      this.page = 1
      // 2. 重发请求
      this.loadEmployee()
    },
    // 自动接收当前的页码
    hCurrentChange(curPage) {
      console.log(curPage)
      // 1. 更新页码
      this.page = curPage
      // 2. 重发请求
      this.loadEmployee()
    }
  }
}
</script>
